import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * <p>
 * </p>
 *
 * @author zhuolin
 * @since 2020/6/9
 */
public class CyclicBarrierDemo {

    public static class Soldier implements Runnable {

        private String solider;

        private final CyclicBarrier cyclicBarrier;

        public Soldier(String solider, CyclicBarrier cyclicBarrier) {
            this.solider = solider;
            this.cyclicBarrier = cyclicBarrier;
        }

        private void doWork() {
            try {
                Thread.sleep(Math.abs(new Random().nextInt() % 10000));
                System.out.println(solider + ":完成任务!"+cyclicBarrier.getNumberWaiting());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

        @Override
        public void run() {
            try {
                System.out.println(solider + "报道！"+cyclicBarrier.getNumberWaiting());
                cyclicBarrier.await();
                doWork();
                cyclicBarrier.await();

            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }

        }
    }

    public static class BarrierRun implements Runnable {

        boolean flag;
        int N;

        public BarrierRun(boolean flag, int n) {
            this.flag = flag;
            N = n;
        }

        @Override
        public void run() {
            if (flag) {
                System.out.println("司令：【士兵】" + N + "个，任务完成");
            } else {
                System.out.println("司令：【士兵】" + N + "个，集合完毕");
                flag = true;
            }
        }
    }

    public static void main(String[] args) {
        final int N = 10;
        Thread[] all = new Thread[N];
        boolean flag = false;
        CyclicBarrier cyclicBarrier = new CyclicBarrier(N, new BarrierRun(flag, N));
//        CyclicBarrier cyclicBarrier = new CyclicBarrier(N);
        System.out.println("队伍集合");
        for (int i = 0; i < N; i++) {
            all[i] = new Thread(new Soldier("士兵" + i, cyclicBarrier));
            all[i].start();
        }

    }
}
